local extension = Package("aaa_steam_3design")
extension.extensionName = "aaa_steam"

local U = require "packages/utility/utility"
local RUtil = require "packages/aaa_fenghou/utility/rfenghou_util"
local DIY = require "packages/diy_utility/diy_utility"

Fk:loadTranslationTable{
  ["aaa_steam_3design"] = "三设吧赛选",
}

local ruanxian = General(extension, "steam__ruanxian", "qun", 3, 3, General.Male) 
local malong = General(extension, "steam__malong", "jin", 4, 4, General.Male) 
local zhaozhi = General(extension, "steam__zhaozhi", "shu", 3, 3, General.Male) 
local Darwin = General(extension, "steam__Darwin", "west", 3, 3, General.Male) 

local function AddWinAudio(general)
  local Win = fk.CreateActiveSkill{ name = general.name.."_win_audio" }
  Win.package = extension
  Fk:addSkill(Win)
end

local sixian = fk.CreateTriggerSkill{
  name = "steam__sixian",
  anim_type = "offensive",
  events = {fk.GameStart},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) 
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
      local cards = {}
      table.insertTable(cards, room:getCardsFromPileByRule("slash|.|.|.|.|."))
      table.insertTable(cards, room:getCardsFromPileByRule("jink|.|.|.|.|."))
      table.insertTable(cards, room:getCardsFromPileByRule("peach|.|.|.|.|."))
      table.insertTable(cards, room:getCardsFromPileByRule("analeptic|.|.|.|.|."))
    if #cards == 4 then
      for _, id in ipairs(cards) do
        room:setCardMark(Fk:getCardById(id), "@@steam__sixian1", 1)
      end
      player:addToPile("steam__sixian_music", cards, true, self.name)
    end
  end,

  refresh_events = {fk.AfterCardsMove},
  can_refresh = function(self, event, target, player, data)
    for _, move in ipairs(data) do
      if move.toArea == Card.DiscardPile then
        for _, info in ipairs(move.moveInfo) do
          return Fk:getCardById(info.cardId):getMark("@@steam__sixian1") > 0 
        end
      end
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    for _, move in ipairs(data) do
      for _, info in ipairs(move.moveInfo) do
        room:setCardMark(Fk:getCardById(info.cardId), "@@steam__sixian1", 0)
      end
    end
  end,
}
local qingtan = fk.CreateViewAsSkill{
  name = "steam__qingtan",
  mute = true,
  anim_type = "switch",
  prompt = "#steam__qingtan-viewas",
  pattern = "slash,jink,peach,analeptic|.|.|.|.|.",
  interaction = function()
  local all_names = {"slash","jink","peach","analeptic"}
  local names = U.getViewAsCardNames(Self, "steam__qingtan", all_names)
  for _, id in ipairs (all_names) do
    if Self:getMark("steam__qingtan_"..id.."-turn") > 0 then
      table.removeOne(names, id)
    end
   end
    if #names > 0 then
      return UI.ComboBox { choices = names, all_choices = all_names }
    end
  end,
  card_filter = Util.FalseFunc,
  view_as = function(self, cards)
    if not self.interaction.data then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = self.name
    return card
  end,
  before_use = function(self, player, use)
    local room = player.room
    player:broadcastSkillInvoke(self.name, 1)
    room:setPlayerMark(player, "steam__qingtan_"..self.interaction.data.."-turn", 1)
    local x = 0
    if self.interaction.data == "slash" then 
      x = 1
    elseif self.interaction.data == "jink" then 
      x = 2
    elseif self.interaction.data == "peach" then 
      x = 3
    elseif self.interaction.data == "analeptic" then 
      x = 4
    end
    if x == 0 then return end
    local cards = room:askForCard(player, x, x, false, self.name, false, ".|.|.|steam__sixian_music", "#steam__qingtan-invoke:::"..x, "steam__sixian_music")
    for _, id in ipairs(cards) do
      if Fk:getCardById(id):getMark("@@steam__sixian1") == 1 then
      room:setCardMark(Fk:getCardById(id), "@@steam__sixian1", 0)
      else
      room:setCardMark(Fk:getCardById(id), "@@steam__sixian1", 1)
    end
    end
    if #table.filter(player:getPile("steam__sixian_music"), function(id)
      return Fk:getCardById(id):getMark("@@steam__sixian1") == 0 end) == 1
    and
    table.find(player:getPile("steam__sixian_music"), function(id) 
      return Fk:getCardById(id):getMark("@@steam__sixian1") == 0
      and Fk:getCardById(id).trueName == self.interaction.data end) then 
        if self.interaction.data == "slash" then 
          player:broadcastSkillInvoke(self.name, 2)
        elseif self.interaction.data == "jink" then 
          player:broadcastSkillInvoke(self.name, 3)
        elseif self.interaction.data == "peach" then 
          player:broadcastSkillInvoke(self.name, 4)
        elseif self.interaction.data == "analeptic" then 
          player:broadcastSkillInvoke(self.name, 5)
        end
      player:drawCards(1, self.name)
      use.extraUse = true
    else
      player:broadcastSkillInvoke(self.name, 6)
      return ""
    end
    end,
  enabled_at_play = function(self, player)
    local all_names = {"slash","jink","peach","analeptic"}
    local names = U.getViewAsCardNames(player, "steam__qingtan", all_names)
    for _, id in ipairs (all_names) do
      if player:getMark("steam__qingtan_"..id.."-turn") > 0 then
        table.removeOne(names, id)
      end
     end
     for _, name in ipairs(names) do
      local to_use = Fk:cloneCard(name)
      if not to_use.skill:canUse(player, to_use, {bypass_times = true , bypass_distances = true}) 
      or player:prohibitUse(to_use) then
      table.removeOne(names, name)
      end
    end
    return #names > 0 and #player:getPile("steam__sixian_music") == 4
  end,
  enabled_at_response = function(self, player, res)
    local all_names = {"slash","jink","peach","analeptic"}
    local names = U.getViewAsCardNames(player, "steam__qingtan", all_names)
    for _, id in ipairs (all_names) do
      if player:getMark("steam__qingtan_"..id.."-turn") > 0 then
        table.removeOne(names, id)
      end
     end
     for _, name in ipairs(names) do
      local to_use = Fk:cloneCard(name)
      return not res and Fk.currentResponsePattern and Exppattern:Parse(Fk.currentResponsePattern):match(to_use) and #player:getPile("steam__sixian_music") == 4
    end
  end,
}
local qingtan_targetmod = fk.CreateTargetModSkill{
  name = "#steam__qingtan_targetmod",
  bypass_times =  function(self, player, skill, scope, card)
    return card and ((skill.trueName == "slash_skill" and scope == Player.HistoryPhase) or (skill.trueName == "analeptic_skill" and scope == Player.HistoryTurn)) 
    and table.contains(card.skillNames, "steam__qingtan")
  end,
  bypass_distances =  function(self, player, skill, card, to)
    return card and table.contains(card.skillNames, "steam__qingtan")
  end,
}
qingtan:addRelatedSkill(qingtan_targetmod)
ruanxian:addSkill(sixian)
ruanxian:addSkill(qingtan)
AddWinAudio(ruanxian)
Fk:loadTranslationTable{
  ["steam__ruanxian"] = "阮咸",
  ["#steam__ruanxian"] = "妙音八达",
  ["cv:steam__ruanxian"] = "张让",
  ["illustrator:steam__ruanxian"] = "恶童",
  ["designer:steam__ruanxian"] = "不能更改",

  ["steam__sixian"] = "四弦",
  [":steam__sixian"] = "锁定技，游戏开始时，你将牌堆中【杀】【闪】【桃】【酒】各一张暗置于武将牌上，称为“弦”。<a href='steam__xian_href'>注释</a>",
  ["steam__qingtan"] = "清弹",
  [":steam__qingtan"] = "每回合每种牌名各限一次，当你需要使用【杀】/【闪】/【桃】/【酒】时，你可以翻面一/二/三/四张“弦”。若仅剩对应牌名的“弦”正面朝上，你摸一张牌并视为使用之（无距离与次数限制）。",
  ["steam__sixian_music"] = "四弦",
  ["@@steam__sixian1"] = "暗弦",
  ["#steam__qingtan-viewas"] = "请选择 清弹 视为使用的基本牌（无距离次数限制，但需要满足技能所示条件，注意，有“暗弦”标记的弦牌处于暗置状态！）",
  ["#steam__qingtan-invoke"] = "清弹：请将 %arg 张“弦”翻面（注意，有“暗弦”标记的弦牌处于暗置状态！）",
  ["steam__xian_href"] = "有“暗弦”标记的弦牌视为处于暗置状态，所有弦开局都添加“暗弦”标记并视为暗置。",

  ["$steam__sixian1"] = "此器四弦十二柱，当奏五音闻九霄！",
  ["$steam__sixian2"] = "此林七友才百斗，当著千文传万世！",
  ["$steam__qingtan1"] = "（开始）宫商角徵羽，尽在一弹一拨之中。",
  ["$steam__qingtan2"] = "（杀）收拨当心画，一声如裂帛！",
  ["$steam__qingtan3"] = "（闪）洛灵凌波步，君子回首顾。",
  ["$steam__qingtan4"] = "（桃）岭南佳果在席，天下美馔失色！",
  ["$steam__qingtan5"] = "（酒）取盆载杜康，杜康与豕，杜康与人！",
  ["$steam__qingtan6"] = "（失败）管短尺黍余，此所以音律不谐也。",
  ["$steam__ruanxian_win_audio"] = "丝竹和鸣，曲水流觞，隐居世外，不为俗世所扰。",
  ["~steam__ruanxian"] = "故友远，草兽偃，杯酒独酌，天年独终...",
} --阮咸

local jizhen = fk.CreateTriggerSkill{
  name = "steam__jizhen",
  mute = true,
  events = {fk.CardUseFinished},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card and (player:getMark("steam__jizhen2_basic") > 0
    or player:getMark("steam__jizhen2_nonbasic") > 0) and (player:getMark("steam__jizhen1_basic") > 0 or player:getMark("steam__jizhen1_nonbasic") > 0)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local skills = {}
      if not player:hasSkill("ex__paoxiao", true) and player:getMark("steam__jizhen1_basic") > 0 then
        table.insert(skills, "ex__paoxiao")
      end
      if not player:hasSkill("ex__longdan", true) and player:getMark("steam__jizhen2_basic") > 0 then
        table.insert(skills, "ex__longdan")
      end
      if not player:hasSkill("bazhen", true) and player:getMark("steam__jizhen1_nonbasic") > 0 and player:getMark("steam__jizhen2_nonbasic") > 0 then
        table.insert(skills, "bazhen")
      end
      room:setPlayerMark(player, "steam__jizhen1_basic", 0)
      room:setPlayerMark(player, "steam__jizhen1_nonbasic", 0)
      room:setPlayerMark(player, "steam__jizhen2_basic", 0)
      room:setPlayerMark(player, "steam__jizhen2_nonbasic", 0)
      room:setPlayerMark(player, "@steam__jizhen", string.format("%s %s", "~", "~"))
    if #skills > 0 then
      if #skills == 1 then
        player:broadcastSkillInvoke(self.name, math.random(2))
      else
        player:broadcastSkillInvoke(self.name, 3)
      end
      room:handleAddLoseSkills(player, table.concat(skills, "|"), nil, true, false)
    end
  end,

  refresh_events = {fk.CardUseFinished},
  can_refresh = function(self, event, target, player, data)
    return target == player and player:hasSkill(self, true) and data.card
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if data.card.type == Card.TypeBasic then
      if player:getMark("steam__jizhen1_basic") == 0 and player:getMark("steam__jizhen1_nonbasic") == 0 then
        room:setPlayerMark(player, "steam__jizhen1_basic", 1)
      elseif player:getMark("steam__jizhen2_basic") == 0 and player:getMark("steam__jizhen2_nonbasic") == 0 then
        room:setPlayerMark(player, "steam__jizhen2_basic", 1)
      end
    elseif data.card.type ~= Card.TypeBasic then
      if player:getMark("steam__jizhen1_basic") == 0 and player:getMark("steam__jizhen1_nonbasic") == 0 then
        room:setPlayerMark(player, "steam__jizhen1_nonbasic", 1)
      elseif player:getMark("steam__jizhen2_basic") == 0 and player:getMark("steam__jizhen2_nonbasic") == 0 then
        room:setPlayerMark(player, "steam__jizhen2_nonbasic", 1)
      end
    end
     room:setPlayerMark(player, "@steam__jizhen", string.format("%s %s",
     (player:getMark("steam__jizhen1_basic") > 0 and "咆哮") or (player:getMark("steam__jizhen1_nonbasic") > 0 and "白板") or "~",
     (player:getMark("steam__jizhen2_basic") > 0 and "龙胆") or (player:getMark("steam__jizhen2_nonbasic") > 0 and "八阵") or "~"))
  end,

  on_acquire = function (self, player, is_start)
    local room = player.room
    room:setPlayerMark(player, "@steam__jizhen", string.format("%s %s", "~", "~"))
  end,

  on_lose = function (self, player, is_death)
    local room = player.room
    room:setPlayerMark(player, "steam__jizhen1_basic", 0)
    room:setPlayerMark(player, "steam__jizhen1_nonbasic", 0)
    room:setPlayerMark(player, "steam__jizhen2_basic", 0)
    room:setPlayerMark(player, "steam__jizhen2_nonbasic", 0)
    room:setPlayerMark(player, "@steam__jizhen", 0)
  end,
}
local pianxiang = fk.CreateTriggerSkill{
  name = "steam__pianxiang",
  mute = true,
  anim_type = "drawcard",
  events = {fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local skills = table.map(table.filter(player.player_skills, function (s)
      return s:isPlayerSkill(player) and s.visible
    end), Util.NameMapper)
    -- 为了避免删除未发动的技能，故做一下区分（甚至注释部分都能拉神张郃的代码用，神张郃的码佬太强太强）
    local skillToStr = function (list)
      return table.map(list, function (s)
        local skill = Fk.skills[s]
        if (skill.frequency == Skill.Limited or skill.frequency == Skill.Wake) and player:usedSkillTimes(s, Player.HistoryGame) > 0 then
          s = "SteamSkillInvoked:::"..s
        end
        return s
      end)
    end
    local returnSkill = function (list)
      return table.map(list, function (s)
        if s:startsWith("SteamSkillInvoked") then
          s = s:split(":::")[2]
        end
        return s
      end)
    end
    skills = skillToStr(skills)
    local tolose = {}
    tolose = room:askForChoices(player, skills, 1, 999, self.name, "#steam__pianxiang-lose", false)
    local printcard = false
    if table.contains(tolose, "steam__jizhen") or table.contains(tolose, "steam__pianxiang") then
      printcard = true
    end
    tolose = returnSkill(tolose)
    if #tolose > 0 then
      player:broadcastSkillInvoke(self.name, math.random(2))
      room:handleAddLoseSkills(player, "-"..table.concat(tolose, "|-"))
      if not player.dead then
      player:drawCards(#tolose, self.name)
      if printcard then
      local cards = U.getUniversalCards(room, "bt", false)
      local use = U.askForUseRealCard(room, player, cards, nil, self.name, "#steam__pianxiang-ask",
        {expand_pile = cards, bypass_times = true, extraUse = true}, true, false)
      if use then
        player:broadcastSkillInvoke(self.name, 3)
        use = {
          card = Fk:cloneCard(use.card.name),
          from = player.id,
          tos = use.tos,
        }
        use.card.skillName = self.name
        room:useCard(use)
      end
      end
      end
    end
  end,
}
malong:addSkill(jizhen)
malong:addSkill(pianxiang)
malong:addRelatedSkill("ex__paoxiao")
malong:addRelatedSkill("ex__longdan")
malong:addRelatedSkill("bazhen")
AddWinAudio(malong)

Fk:loadTranslationTable{
  ["steam__malong"] = "马隆",
  ["#steam__malong"] = "孤师妙器",
  ["cv:steam__malong"] = "幽蝶化烬",
  ["illustrator:steam__malong"] = "恶童",
  ["designer:steam__malong"] = "亚里士缺德",

  ["steam__jizhen"] = "机阵",
  [":steam__jizhen"] = "锁定技，你每累计使用两张牌后，根据所满足的条件获得对应技能：第一张为基本牌--“咆哮”；第二张为基本牌--“龙胆”；均不为基本牌--“八阵”。",
  ["steam__pianxiang"] = "偏箱",
  [":steam__pianxiang"] = "每回合结束时，你可以失去任意个技能，然后摸等量张牌。若你因此失去“机阵”或“偏箱”，你视为使用一张基本牌或普通锦囊牌。",
  ["@steam__jizhen"] = "机阵",
  ["SteamSkillInvoked"] = "%arg(已发动)",
  ["#steam__pianxiang-lose"] = "偏箱：请失去至少一个技能，摸等量张牌，失去机阵或偏箱则额外视为使用基本牌或普通锦囊牌。",
  ["#steam__pianxiang-ask"] = "偏箱：请使用一张基本牌或普通锦囊牌！",

  ["$steam__jizhen1"] = "云附于地，则知无形。变为翔鸟，其状乃成。",
  ["$steam__jizhen2"] = "风无正形，附之于天。变而为蛇，其意渐玄。",
  ["$steam__jizhen3"] = "（获得两个）鸷鸟击搏，必先翱翔。势凌霄汉，飞禽伏藏。",
  ["$steam__pianxiang1"] = "阔构营，狭垒箱，伏弩齐射，教彼进退两难！",
  ["$steam__pianxiang2"] = "着犀甲，布磁石，诈败诱之，要其有来无回！",
  ["$steam__pianxiang3"] = "（用牌）中原之工巧，蛮儿焉能究其理？",
  ["$steam__malong_win_audio"] = "边患荡除，百姓乐业，用兵得此，善莫大焉！",
  ["$ex__paoxiao_steam__malong"] = "风能鼓动，万物惊焉；蛇能围绕，三军惧焉。",
  ["$ex__longdan_steam__malong"] = "潜则不测，动则无穷。阵形亦然，象名其龙。",
  ["$bazhen_steam__malong"] = "可握则握，可施则施。千变万化，敌莫能知。",
  ["~steam__malong"] = "匹夫！老农逐豕尚不执朽木，况我良将锐士乎！",
} --马隆

--赵直有关结算：称梦角色同时最多存在一个，已有的可以转移，已死亡则下个回合开始可以重新指定

local chengmeng = fk.CreateTriggerSkill{
  name = "steam__chengmeng",
  mute = true,
  events = {fk.BeforeChainStateChange, fk.TurnStart, fk.Damaged, fk.RoundStart},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    local room = player.room
    if not player:hasSkill(self) then return false end
    if event == fk.BeforeChainStateChange then
      return target:getMark("@@chengmeng_lost-round") > 0 and target.chained
    elseif event == fk.TurnStart then
      return not player:isNude() and #table.filter(room.alive_players, function(p)
        return p:getMark("@@chengmeng-round") > 0 end) <= 1
    elseif event == fk.Damaged then
      return target:getMark("@@chengmeng-round") > 0 and table.find(room.alive_players, function(p)
      return p ~= target and p:isWounded() and p.hp == p:getHandcardNum() end)
    else
      return not table.find(player.room.alive_players, function(p) return p:getMark("@@chengmeng-round") > 0 end)
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if event == fk.BeforeChainStateChange then
      return true
    elseif event == fk.TurnStart then
    local card = room:askForDiscard(player, 1, 1, true, self.name, true, ".|.|heart,diamond", "steam__chengmeng-ask")
    if #card > 0 and #table.filter(room.alive_players, function(p) return p:getMark("@@chengmeng-round") == 0 end) > 0 then
    local to = room:askForChoosePlayers(player, table.map(table.filter(room.alive_players, function(p)
      return p:getMark("@@chengmeng-round") == 0 end), Util.IdMapper), 1, 1,
      "steam__chengmeng-redefine", self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
      end
    end
    elseif event == fk.Damaged then
    local to = room:askForChoosePlayers(player, table.map(table.filter(room.alive_players, function(p)
      return p ~= target and p:isWounded() and p.hp == p:getHandcardNum() end), Util.IdMapper), 1, 1,
      "steam__chengmeng-recover", self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
    else
    local to = room:askForChoosePlayers(player, table.map(player.room:getAlivePlayers(), Util.IdMapper), 1, 1, 
    "steam__chengmeng-invoke", self.name, false)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.BeforeChainStateChange then
      player:broadcastSkillInvoke(self.name, 4)
      return true
    elseif event == fk.TurnStart then
      player:broadcastSkillInvoke(self.name, 3)
      for _, p in ipairs(room:getAlivePlayers()) do
        if p:getMark("@@chengmeng-round") > 0 then
        room:setPlayerMark(p, "@@chengmeng-round", 0)
        room:setPlayerMark(p, "@@chengmeng_lost-round", 1)
        p:setChainState(true)
        end
      end
      local to = room:getPlayerById(self.cost_data)
      room:setPlayerMark(to, "@@chengmeng-round", 1)
    elseif event == fk.Damaged then
      player:broadcastSkillInvoke(self.name, 2)
      local to = room:getPlayerById(self.cost_data)
      room:recover({
        who = to,
        num = 1,
        recoverBy = player,
        skillName = self.name
      })
    else
      player:broadcastSkillInvoke(self.name, 1)
      local to = room:getPlayerById(self.cost_data)
      room:setPlayerMark(to, "@@chengmeng-round", 1)
    end
  end,
}

local yuexin = fk.CreateActiveSkill{
  name = "steam__yuexin",
  anim_type = "drawcard",
  prompt = "#steam__yuexin-active",
  card_num = 0,
  target_num = 1,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) < 1
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, selected_cards)
    return #selected == 0 and not Fk:currentRoom():getPlayerById(to_select):isKongcheng()
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    target:drawCards(target:getHandcardNum(), self.name)
    local x = 0
    if not target:isKongcheng() then
    target:showCards(target.player_cards[target.Hand])
    local ids = {}
    for _, id in ipairs(target.player_cards[target.Hand]) do
      if Fk:getCardById(id).type == Card.TypeBasic then
      table.insert(ids, id)
      end
    end
    if #ids > 0 then
      x = #ids
      room:throwCard(ids, self.name, target, target)
    end
    end
    if x ~= target.hp then
      room:damage{
        from = player,
        to = target,
        damage = 1,
        damageType = fk.FireDamage,
        skillName = self.name,
      }
    end
    end,
}
zhaozhi:addSkill(chengmeng)
zhaozhi:addSkill(yuexin)
Fk:loadTranslationTable{
  ["steam__zhaozhi"] = "赵直",
  ["#steam__zhaozhi"] = "大梦与初",
  ["cv:steam__zhaozhi"] = "官方",
  ["illustrator:steam__zhaozhi"] = "白",
  ["designer:steam__zhaozhi"] = "风尘慰酒",

  ["steam__chengmeng"] = "称梦",
  [":steam__chengmeng"] = "轮次开始时，你可以选择一名角色。本轮你以此法选择的角色受到伤害后，你可以令另一名手牌数与体力值相等的角色回复1点体力。"..
  "一个回合开始时，你可以弃置一张红色牌，变更本轮你以此法选择的角色，然后原角色横置且本轮始终横置。",
  ["steam__yuexin"] = "曰心",
  [":steam__yuexin"] = "出牌阶段限一次，你可以令一名有手牌的角色将手牌数翻倍，然后其展示手牌，弃置其中的基本牌，若弃置牌数不等于其的体力值，你对其造成1点火焰伤害。",

  ["steam__chengmeng-ask"] = "是否发动 称梦，弃置一张红色牌，然后转移“称梦”标记。",
  ["steam__chengmeng-redefine"] = "发动 称梦，请转移“称梦”标记。",
  ["steam__chengmeng-recover"] = "是否发动 称梦，令一名符合条件的角色回复1点体力？",
  ["steam__chengmeng-invoke"] = "发动 称梦，令一名角色获得“称梦”标记。",
  ["@@chengmeng-round"] = "称梦",
  ["@@chengmeng_lost-round"] = "失去称梦",
  ["#steam__yuexin-active"] = "发动 曰心，令一名有手牌的角色翻倍手牌数，然后其弃置所有基本牌并有可能受到你的火焰伤害。",

  ["$steam__chengmeng1"] = "（添加标记）壮、善、智、明、仁，人虽同而性各异。",
  ["$steam__chengmeng2"] = "（回复体力）窥天之道者，天自怜之。",
  ["$steam__chengmeng3"] = "（转移标记）既为命数之咽喉，不受天数之所咎。",
  ["$steam__chengmeng4"] = "（重新横置）梦境渺如水月，难辨其间虚实。",
  ["$steam__yuexin1"] = "常怀敬畏于怪力，不坠清明于乱神。",
  ["$steam__yuexin2"] = "物有其征，日所思之、夜所梦之。",
  ["~steam__zhaozhi"] = "临渊解梦，何如直挂云帆？",
} --赵直

local ziranxuanze_active = fk.CreateActiveSkill{
  name = "steam__ziranxuanze_active",
  card_num = 0,
  min_target_num = 1,
  max_target_num = 999,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    local target = Fk:currentRoom():getPlayerById(to_select)
    if #selected == 0 then
      return true
    else
      for _, id in ipairs(selected) do
        local p = Fk:currentRoom():getPlayerById(id)
        if target.kingdom == p.kingdom then
          return false
        end
      end
      return true
    end
  end,
}
Fk:addSkill(ziranxuanze_active)
local ziranxuanze = fk.CreateTriggerSkill{
  name = "steam__ziranxuanze",
  mute = true,
  anim_type = "special",
  events = {fk.RoundStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self)
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local _, dat = room:askForUseActiveSkill(player, "steam__ziranxuanze_active", "#steam__ziranxuanze-active", true, nil, false)
    if dat then
      self.cost_data = {tos = dat.targets, choice = dat.interaction}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local tos = self.cost_data.tos
    room:sortPlayersByAction(tos)
    tos = table.map(tos, Util.Id2PlayerMapper)

    local choices = {}
    local mark = player:getTableMark("@steam__ziranxuanze")
    for _, id in ipairs(mark) do
      table.insertIfNeed(choices, id)
    end
    local result = U.askForJointChoice(tos, choices, self.name,
      "#steam__ziranxuanze_choose")
 
    local x = 0
    local y = 0
    local z = 0
    if not table.contains(mark, "Darwin_rende") then
      x = -1
    end
    if not table.contains(mark, "Darwin_jianxiong") then
      y = -1
    end
    if not table.contains(mark, "Darwin_zhiheng") then
      z = -1
    end
    for _, p in ipairs(tos) do
      local choice = result[p.id]
      if choice == "Darwin_rende" then
        x = x + 1
      elseif choice == "Darwin_jianxiong" then
        y = y + 1
      elseif choice == "Darwin_zhiheng" then
        z = z + 1
      end
    end
    local nochoices = {}
    local min_value --非负值：未被移除；负值：已移除；非负值中最小的选项加入可删除名单 
    if x >= 0 and y >= 0 and z >= 0 then
    min_value = math.min(x, y, z)
    elseif x >= 0 and y >= 0 and z < 0 then
    min_value = math.min(x, y)
    elseif x >= 0 and y < 0 and z >= 0 then
    min_value = math.min(x, z)
    elseif x < 0 and y >= 0 and z >= 0 then
    min_value = math.min(y, z)
    elseif x >= 0 and y < 0 and z < 0 then
    min_value = x
    elseif x < 0 and y >= 0 and z < 0 then
    min_value = y
    elseif x < 0 and y < 0 and z >= 0 then
    min_value = z
    end
    if min_value == x then
      table.insertIfNeed(nochoices, "Darwin_rende")
    end
    if min_value == y then
      table.insertIfNeed(nochoices, "Darwin_jianxiong")
    end
    if min_value == z then
      table.insertIfNeed(nochoices, "Darwin_zhiheng")
    end
    local clear = false
    if player:getMark("@@steam__xungensuyuan1") == 0 and player:getMark("@@steam__xungensuyuan2") == 0 and player:getMark("@@steam__xungensuyuan3") == 0 then
      clear = true --判断一下是否已经有修改寻根溯源的记录，防止寻根溯源同时等于仁德和制衡（问就是二合一了）
    end
    if #mark > 1 and #nochoices > 0 then
    local nochoice = room:askForChoice(player, nochoices, self.name, "#steam__ziranxuanze_remove", false, {"Darwin_rende", "Darwin_jianxiong", "Darwin_zhiheng"})
    if #mark == 3 and nochoice == "Darwin_rende" and clear then
      room:setPlayerMark(player, "@@steam__xungensuyuan1", 1)
    elseif #mark == 3 and nochoice == "Darwin_jianxiong" then
      room:setPlayerMark(player, "@@steam__xungensuyuan2", 1)
    elseif #mark == 3 and nochoice == "Darwin_zhiheng" then
      room:setPlayerMark(player, "@@steam__xungensuyuan3", 1)
    end
    table.removeOne(mark, nochoice)
    room:setPlayerMark(player, "@steam__ziranxuanze", #mark > 0 and mark or 0)
    end
    for _, p in ipairs(tos) do
      local choice = result[p.id]
      if table.contains(mark, choice) then
      if choice == "Darwin_rende" then
        room:handleAddLoseSkills(p, "Darwin_rende", nil, false, true)
      elseif choice == "Darwin_jianxiong" then
        room:handleAddLoseSkills(p, "Darwin_jianxiong", nil, false, true)
      elseif choice == "Darwin_zhiheng" then
        room:handleAddLoseSkills(p, "Darwin_zhiheng", nil, false, true)
      end
      elseif not table.contains(mark, choice) then
        room:handleAddLoseSkills(p, "Darwin_benghuai", nil, false, true)
      end
    end
  end,

  refresh_events = {fk.RoundEnd},
  global = true,
  can_refresh = function(self, event, target, player, data)
    return true
  end,
  on_refresh = function(self, event, target, player, data)
    for _, p in ipairs(player.room:getAlivePlayers()) do
      player.room:handleAddLoseSkills(p, "-Darwin_rende", nil, false, true)
      player.room:handleAddLoseSkills(p, "-Darwin_jianxiong", nil, false, true)
      player.room:handleAddLoseSkills(p, "-Darwin_zhiheng", nil, false, true)
      player.room:handleAddLoseSkills(p, "-Darwin_benghuai", nil, false, true)
    end
  end,

  on_acquire = function (self, player, is_start)
    player.room:setPlayerMark(player, "@steam__ziranxuanze", {"Darwin_rende", "Darwin_jianxiong", "Darwin_zhiheng"})
  end,
  on_lose = function (self, player, is_death)
    local room = player.room
    room:setPlayerMark(player, "@steam__ziranxuanze", 0)
  end,
}
Darwin:addSkill(ziranxuanze)

--设计者的意思是可以获得对应技能或者修改本体效果，考虑到多获得技能又要被神华佗之类的蹭到，就把三个技能的效果耦合了。
local xungensuyuan = fk.CreateActiveSkill{
  name = "steam__xungensuyuan",
  anim_type = "special",
  prompt = function(self)
    if Self:getMark("@@steam__xungensuyuan1") == 1 then
      return "#xungensuyuan_rende"
    elseif Self:getMark("@@steam__xungensuyuan3") == 1 then
      return "#xungensuyuan_zhiheng"
    end
  end,
  interaction = function(self)
    local names = {}
    if Self:getMark("@@steam__xungensuyuan1") == 1 then
      table.insert(names, "xungensuyuan_rende")
    end
    if Self:getMark("@@steam__xungensuyuan3") == 1 then
      table.insert(names, "xungensuyuan_zhiheng")
    end
    if #names > 0 then
    return UI.ComboBox {choices = names}
    end
  end,
  can_use = function(self, player, card, extra_data)
    return 
    (table.find(Fk:currentRoom().alive_players, function(p) return p:getMark("_xungensuyuan_rende-phase") == 0 end) 
    and player:getMark("@@steam__xungensuyuan1") == 1) --仁德部分的判断
    or 
    (player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and player:getMark("@@steam__xungensuyuan3") == 1) --制衡部分的判断
  end,
  card_filter = function(self, to_select, selected)
    if self.interaction.data == "xungensuyuan_rende" then
      return table.contains(Self:getCardIds("h"), to_select)
  elseif self.interaction.data == "xungensuyuan_zhiheng" then
      return not Self:prohibitDiscard(Fk:getCardById(to_select))
    end
  end,
  target_filter = function(self, to_select, selected)
    return self.interaction.data == "xungensuyuan_rende" and 
      #selected == 0 and to_select ~= Self.id and Fk:currentRoom():getPlayerById(to_select):getMark("_xungensuyuan_rende-phase") == 0
  end,
  feasible = function(self, selected, selected_cards)
    return #selected_cards > 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    if self.interaction.data == "xungensuyuan_rende" then
    local cards = effect.cards
    local marks = player:getMark("_xungensuyuan_rende_cards-phase")
    room:moveCardTo(cards, Player.Hand, target, fk.ReasonGive, self.name, nil, false)
    room:addPlayerMark(player, "_xungensuyuan_rende_cards-phase", #cards)
    room:setPlayerMark(target, "_xungensuyuan_rende-phase", 1)
    if marks < 2 and marks + #cards >= 2 then
      cards = U.getUniversalCards(room, "b", false)
      local use = U.askForUseRealCard(room, player, cards, nil, self.name, "#xungensuyuan_rende-ask",
        {expand_pile = cards, bypass_times = false, extraUse = false}, true, true)
      if use then
        use = {
          card = Fk:cloneCard(use.card.name),
          from = player.id,
          tos = use.tos,
        }
        use.card.skillName = self.name
        room:useCard(use)
      end
    end
  elseif self.interaction.data == "xungensuyuan_zhiheng" then
    local hand = player:getCardIds(Player.Hand)
    local more = #hand > 0
    for _, id in ipairs(hand) do
      if not table.contains(effect.cards, id) then
        more = false
        break
      end
    end
    room:throwCard(effect.cards, self.name, player, player)
    if not player.dead then
    room:drawCards(player, #effect.cards + (more and 1 or 0), self.name)
    end
  end
  end,
}
local xungensuyuan_trigger = fk.CreateTriggerSkill{
  name = "#steam__xungensuyuan_trigger",
  anim_type = "masochism",
  events = {fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player:getMark("@@steam__xungensuyuan2") == 1
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#steam__xungensuyuan_jianxiong")
  end,
  on_use = function(self, event, target, player, data)
    if data.card and U.hasFullRealCard(player.room, data.card) then
      player.room:obtainCard(player.id, data.card, true, fk.ReasonJustMove)
    end
    player:drawCards(1, self.name)
  end,
}
xungensuyuan:addRelatedSkill(xungensuyuan_trigger)
Darwin:addSkill(xungensuyuan)

--咨询了一下设计者，他觉得有仁德再获得/不获得都可以，这次先写一个可以重复技能的版本，以观后效
--（暂时没搞明白多个同效果同名称的技能写法，这里就改了四个只能因此获得的技能出来）

local rende = fk.CreateActiveSkill{
  name = "Darwin_rende",
  anim_type = "support",
  min_card_num = 1,
  target_num = 1,
  prompt = "#Darwin_rende",
  card_filter = function(self, to_select, selected)
    return table.contains(Self:getCardIds("h"), to_select)
  end,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and to_select ~= Self.id and Fk:currentRoom():getPlayerById(to_select):getMark("_Darwin_rende-phase") == 0
  end,
  on_use = function(self, room, effect)
    local target = room:getPlayerById(effect.tos[1])
    local player = room:getPlayerById(effect.from)
    local cards = effect.cards
    local marks = player:getMark("_Darwin_rende_cards-phase")
    room:moveCardTo(cards, Player.Hand, target, fk.ReasonGive, self.name, nil, false)
    room:addPlayerMark(player, "_Darwin_rende_cards-phase", #cards)
    room:setPlayerMark(target, "_Darwin_rende-phase", 1)
    if marks < 2 and marks + #cards >= 2 then
      cards = U.getUniversalCards(room, "b", false)
      local use = U.askForUseRealCard(room, player, cards, nil, self.name, "#Darwin_rende-ask",
        {expand_pile = cards, bypass_times = false, extraUse = false}, true, true)
      if use then
        use = {
          card = Fk:cloneCard(use.card.name),
          from = player.id,
          tos = use.tos,
        }
        use.card.skillName = self.name
        room:useCard(use)
      end
    end
  end,
}
local jianxiong = fk.CreateTriggerSkill{
  name = "Darwin_jianxiong",
  anim_type = "masochism",
  events = {fk.Damaged},
  on_use = function(self, event, target, player, data)
    if data.card and U.hasFullRealCard(player.room, data.card) then
      player.room:obtainCard(player.id, data.card, true, fk.ReasonJustMove)
    end
    player:drawCards(1, self.name)
  end,
}
local zhiheng = fk.CreateActiveSkill{
  name = "Darwin_zhiheng",
  anim_type = "drawcard",
  min_card_num = 1,
  target_num = 0,
  prompt = "#Darwin_zhiheng",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = function(self, to_select, selected)
    return not Self:prohibitDiscard(Fk:getCardById(to_select))
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local hand = player:getCardIds(Player.Hand)
    local more = #hand > 0
    for _, id in ipairs(hand) do
      if not table.contains(effect.cards, id) then
        more = false
        break
      end
    end
    room:throwCard(effect.cards, self.name, player, player)
    if not player.dead then
      room:drawCards(player, #effect.cards + (more and 1 or 0), self.name)
    end
  end
}
local benghuai = fk.CreateTriggerSkill{
  name = "Darwin_benghuai",
  anim_type = "negative",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Finish and
      table.find(player.room.alive_players, function(p) return p.hp < player.hp end)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local choice = room:askForChoice(player, {"loseMaxHp", "loseHp"}, self.name)
    if choice == "loseMaxHp" then
      room:changeMaxHp(player, -1)
    else
      room:loseHp(player, 1, self.name)
    end
  end,
}
Fk:addSkill(rende)
Fk:addSkill(jianxiong)
Fk:addSkill(zhiheng)
Fk:addSkill(benghuai)

Fk:loadTranslationTable{
  ["steam__Darwin"] = "达尔文",
  ["#steam__Darwin"] = "能心演天",
  ["cv:steam__Darwin"] = "暂无",
  ["illustrator:steam__Darwin"] = "豆包AI",
  ["designer:steam__Darwin"] = "abeeabee",

  ["steam__ziranxuanze"] = "自然选择",
  [":steam__ziranxuanze"] = "轮次开始时，你可以令任意名势力各不相同的角色同时选择获得“仁德”，“奸雄”，“制衡”中的一个技能直至本轮结束，若选项数不为1，"..
  "你删除一个本次被选择次数最少的选项，选择此项的角色改为获得“崩坏”直至本轮结束。",
  ["steam__xungensuyuan"] = "寻根溯源",
  [":steam__xungensuyuan"] = "锁定技，你本局首次删除“自然选择”的选项后，本技能视为被删除项对应的技能。",
  ["steam__ziranxuanze_active"] = "自然选择",
  ["#steam__ziranxuanze-active"] = "自然选择：是否选择任意名势力各不相同的角色？",
  ["#steam__ziranxuanze_choose"] = "自然选择：请选择本轮你想获得的一个技能，若你选择的选项被选择次数最少，则改为本轮获得“崩坏”！",
  ["#steam__ziranxuanze_remove"] = "自然选择：请选择本轮被选择次数最少的一个技能选项，移除之！",
  ["@steam__ziranxuanze"] = "",
  ["@@steam__xungensuyuan1"] = "寻根溯源 仁德",
  ["@@steam__xungensuyuan2"] = "寻根溯源 奸雄",
  ["@@steam__xungensuyuan3"] = "寻根溯源 制衡",
  ["#steam__xungensuyuan_trigger"] = "寻根溯源",
  ["xungensuyuan_rende"] = "执行仁德效果",
  ["xungensuyuan_zhiheng"] = "执行制衡效果",
  ["#xungensuyuan_rende"] = "此技能视为仁德，请选择任意张手牌交给一名其他角色，若本阶段你首次因此交出至少两张牌，你可以视为使用有次数限制的基本牌。",
  ["#xungensuyuan_zhiheng"] = "此技能视为制衡，请选择任意张牌弃置，然后摸等量张牌，若你弃置所有手牌，此次摸牌数量+1。",
  ["#xungensuyuan_rende-ask"] = "寻根溯源：你可视为使用一张基本牌",
  ["#steam__xungensuyuan_jianxiong"] = "寻根溯源：此技能视为奸雄，是否发动本技能，收回对你造成伤害的牌（若有），然后摸一张牌？",

  ["Darwin_rende"] = "仁德",
  [":Darwin_rende"] = "出牌阶段每名角色限一次，你可以将任意张手牌交给一名其他角色，每阶段你以此法给出第二张牌时，你可以视为使用一张基本牌。",
  ["#Darwin_rende"] = "仁德：将任意张手牌交给一名角色，若此阶段交出达到两张，你可以视为使用一张基本牌",
  ["#Darwin_rende-ask"] = "仁德：你可视为使用一张基本牌",
  ["Darwin_jianxiong"] = "奸雄",
  [":Darwin_jianxiong"] = "当你受到伤害后，你可以获得对你造成伤害的牌并摸一张牌。",
  ["Darwin_zhiheng"] = "制衡",
  [":Darwin_zhiheng"] = "出牌阶段限一次，你可以弃置任意张牌并摸等量的牌。若你以此法弃置所有手牌，你多摸一张牌。",
  ["#Darwin_zhiheng"] = "制衡：你可以弃置任意张牌并摸等量的牌，若弃置了所有的手牌，多摸一张牌",
  ["Darwin_benghuai"] = "崩坏",
  [":Darwin_benghuai"] = "锁定技，结束阶段，若你不是体力值最小的角色，你选择：1.减1点体力上限；2.失去1点体力。",
  ["loseMaxHp"] = "减1点体力上限",
  ["loseHp"] = "失去1点体力",

} --达尔文
return extension
